package xiaojian.toolkit.unit;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.io.Resource;

import xiaojian.toolkit.util.ExceptionUtils;

public class AppContextInitor {
	private static final Logger LOG = LoggerFactory
			.getLogger(AppContextInitor.class);
	private final ApplicationContext _root;

	public AppContextInitor(ApplicationContext root) {
		this._root = root;
		this._appctx = root;
	}

	public void setLocations(Resource[] locations) {
		this._locations = locations;
	}

	public void init() {
		if ((this._locations != null) && (this._locations.length > 0)) {
			GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
			try {
				ctx.setParent(this._root);
				ctx.load(this._locations);
				ctx.refresh();
				this._appctx = ctx;
				if (!LOG.isDebugEnabled()) {
					return;
				}
				LOG.debug("create Application Context {} succeed.",
						Arrays.toString(this._locations));
			} catch (Exception e) {
				LOG.error(
						"exception when create application context {}, detail: {}",
						Arrays.toString(this._locations),
						ExceptionUtils.exception2detail(e));
			}
		} else if (LOG.isDebugEnabled()) {
			LOG.debug("_location is null, no application context create.");
		}
	}

	public ApplicationContext getApplicationContext() {
		return this._appctx;
	}

	private Resource[] _locations = null;
	private ApplicationContext _appctx = null;
}
